/**
 * 会话管理API客户端
 * 
 * 用途：负责处理会话管理相关的HTTP请求，包括创建新会话
 * 方法：使用OkHttp库进行网络请求，Gson进行JSON序列化
 * 原理：通过POST请求创建新的脑波监测会话，获取session_uuid用于后续数据发送
 */
package com.example.brain_wave.bluetooth.api

import com.google.gson.Gson
import kotlinx.coroutines.*
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
import java.io.IOException
import com.example.brain_wave.config.AppConfig
import android.content.Context
import android.util.Log

/**
 * 创建会话请求数据
 */
data class CreateSessionRequest(
    val room_id: String,
    val user_id: String? = null
)

/**
 * 会话响应数据
 */
data class SessionResponse(
    val id: String,
    val room_id: String,
    val user_id: String?,
    val start_time: String,
    val end_time: String?,
    val total_seconds: Int?,
    val status: String
)

class SessionApiClient(private val context: Context) {
    
    private val appConfig = AppConfig.getInstance(context)
    
    private val client = OkHttpClient.Builder()
        .connectTimeout(appConfig.connectTimeout.toLong(), java.util.concurrent.TimeUnit.SECONDS)
        .writeTimeout(appConfig.writeTimeout.toLong(), java.util.concurrent.TimeUnit.SECONDS)
        .readTimeout(appConfig.readTimeout.toLong(), java.util.concurrent.TimeUnit.SECONDS)
        .build()
    
    private val gson = Gson()
    private val mediaType = "application/json; charset=utf-8".toMediaType()
    
    // 会话管理API配置
    private var baseUrl: String = appConfig.sessionApiBaseUrl
    private var sessionEndpoint: String = appConfig.sessionApiEndpoint
    
    // 回调函数
    private var onSessionCreated: ((SessionResponse) -> Unit)? = null
    private var onError: ((String) -> Unit)? = null
    
    /**
     * 设置API基础URL
     */
    fun setBaseUrl(url: String) {
        baseUrl = url.trimEnd('/')
    }
    
    /**
     * 设置会话创建成功回调
     */
    fun setOnSessionCreated(callback: (SessionResponse) -> Unit) {
        onSessionCreated = callback
    }
    
    /**
     * 设置错误回调
     */
    fun setOnError(callback: (String) -> Unit) {
        onError = callback
    }
    
    /**
     * 创建新会话
     */
    fun createSession(roomId: String, userId: String? = null) {
        CoroutineScope(Dispatchers.IO).launch {
          try {
                println("🚀 开始创建会话请求，房间ID: $roomId, 用户ID: $userId")
                println("🔗 基础URL: $baseUrl")
                println("📍 端点: $sessionEndpoint")
                println("🌐 完整请求URL: $baseUrl$sessionEndpoint")
                
                // 检查baseUrl是否为空
                if (baseUrl.isEmpty()) {
                    Log.e("SessionApiClient", "❌ 错误：baseUrl为空，无法发送请求")
                    CoroutineScope(Dispatchers.Main).launch {
                        onError?.invoke("会话API基础URL未配置")
                    }
                    return@launch
                }
                 Log.e("SessionApiClient", "√ sessionEndpoint = $sessionEndpoint")
                val request = CreateSessionRequest(
                    room_id = roomId,
                    user_id = userId
                )
                
                val json = gson.toJson(request)
                println("📝 请求JSON: $json")
                
                val requestBody = json.toRequestBody(mediaType)
                
                val httpRequest = Request.Builder()
                    .url("$baseUrl$sessionEndpoint")
                    .post(requestBody)
                    .addHeader("Content-Type", "application/json")
                    .build()
                
                client.newCall(httpRequest).enqueue(object : Callback {
                    override fun onFailure(call: Call, e: IOException) {
                        Log.e("SessionApiClient", "❌ 网络请求失败: ${e.message}")
                        println("❌ 网络请求失败: ${e.message}")
                        e.printStackTrace()
                        CoroutineScope(Dispatchers.Main).launch {
                            onError?.invoke("会话创建失败: ${e.message}")
                        }
                    }
                    
                    override fun onResponse(call: Call, response: Response) {
                        CoroutineScope(Dispatchers.Main).launch {
                            try {
                                println("📨 收到响应，状态码: ${response.code}")
                                println("📨 响应消息: ${response.message}")
                                println("📨 响应是否成功: ${response.isSuccessful}")
                                
                                val responseBody = response.body?.string()
                                println("📄 响应内容: $responseBody")
                                println("📄 响应内容长度: ${responseBody?.length ?: 0}")
                                println("📄 响应内容是否为null: ${responseBody == null}")
                                
                                if (response.isSuccessful) {
                                    try {
                                        if (responseBody.isNullOrEmpty()) {
                                            println("❌ 响应内容为空或null")
                                            onError?.invoke("服务器返回空响应")
                                            return@launch
                                        }
                                        
                                        println("🔄 开始解析JSON响应...")
                                        val sessionResponse = gson.fromJson(responseBody, SessionResponse::class.java)
                                        
                                        if (sessionResponse == null) {
                                            println("❌ JSON解析结果为null")
                                            onError?.invoke("会话响应解析失败: 解析结果为null")
                                            return@launch
                                        }
                                        
                                        if (sessionResponse.id.isNullOrEmpty()) {
                                            println("❌ 会话ID为空或null")
                                            onError?.invoke("会话响应解析失败: 会话ID为空")
                                            return@launch
                                        }
                                        
                                        println("✅ 会话创建成功，ID: ${sessionResponse.id}")
                                        println("✅ 会话详情: room_id=${sessionResponse.room_id}, user_id=${sessionResponse.user_id}, status=${sessionResponse.status}")
                                        onSessionCreated?.invoke(sessionResponse)
                                    } catch (e: Exception) {
                                        Log.e("SessionApiClient", "❌ 响应解析失败: ${e.message}")
                                        println("❌ 响应解析失败: ${e.message}")
                                        println("❌ 异常类型: ${e.javaClass.simpleName}")
                                        println("❌ 异常堆栈: ${e.stackTrace.joinToString("\n")}")
                                        e.printStackTrace()
                                        onError?.invoke("会话响应解析失败: ${e.message}")
                                    }
                                } else {
                                    val errorMessage = "会话创建失败: HTTP ${response.code} - ${response.message}"
                                    Log.e("SessionApiClient", "❌ $errorMessage")
                                    println("❌ $errorMessage")
                                    println("❌ 响应内容: $responseBody")
                                    onError?.invoke(errorMessage)
                                }
                            } catch (e: Exception) {
                                Log.e("SessionApiClient", "❌ 处理响应时发生异常: ${e.message}")
                                println("❌ 处理响应时发生异常: ${e.message}")
                                println("❌ 异常类型: ${e.javaClass.simpleName}")
                                println("❌ 异常详情: ${e.toString()}")
                                println("❌ 异常是否为null: ${e.message == null}")
                                if (e.message == null) {
                                    println("❌ 检测到null异常消息，可能是NullPointerException")
                                    println("❌ 异常堆栈: ${e.stackTrace.joinToString("\n")}")
                                }
                                e.printStackTrace()
                                onError?.invoke("处理响应时发生异常: ${e.message ?: "未知异常"}")
                            }
                        }
                    }
                })
                
            } catch (e: Exception) {
                Log.e("SessionApiClient", "❌ 构建请求时发生异常: ${e.message}")
                e.printStackTrace()
                withContext(Dispatchers.Main) {
                    onError?.invoke("会话请求构建失败: ${e.message}")
                }
            }
        }
    }
    
    /**
     * 同步创建会话（用于测试）
     */
    suspend fun createSessionSync(roomId: String, userId: String? = null): Result<SessionResponse> = withContext(Dispatchers.IO) {
        try {
            val request = CreateSessionRequest(
                room_id = roomId,
                user_id = userId
            )
            
            val json = gson.toJson(request)
            val requestBody = json.toRequestBody(mediaType)
            
            val httpRequest = Request.Builder()
                .url("$baseUrl$sessionEndpoint")
                .post(requestBody)
                .addHeader("Content-Type", "application/json")
                .build()
            
            val response = client.newCall(httpRequest).execute()
            
            if (response.isSuccessful) {
                val responseBody = response.body?.string() ?: ""
                val sessionResponse = gson.fromJson(responseBody, SessionResponse::class.java)
                Result.success(sessionResponse)
            } else {
                Result.failure(Exception("会话创建失败: ${response.code} ${response.message}"))
            }
        } catch (e: Exception) {
            Result.failure(e)
        }
    }
    
    /**
     * 测试会话API连接
     */
    suspend fun testConnection(): Boolean = withContext(Dispatchers.IO) {
        try {
            val request = Request.Builder()
                .url("$baseUrl/health")
                .get()
                .build()
            
            val response = client.newCall(request).execute()
            response.isSuccessful
        } catch (e: Exception) {
            false
        }
    }
}